<?php

/**
 * MyAccountController is the default controller for this application
 */
class MyAccountController extends CustomControllerBase {
	
	/**
	 * UsersDataService Object
	 *
	 * @var UsersDataService object
	 */
	public $usersDataService = null;
	
	/**
	 * AddressDataService Object
	 *
	 * @var AddressDataService object
	 */
	public $addressDataService = null;
	
	/**
	 * CountryDataService Object
	 *
	 * @var CountryDataService object
	 */
	public $countryDataService = null;
	
	/**
	 * StateDataService Object
	 *
	 * @var StateDataService object
	 */
	public $stateDataService = null;
	
	/**
	 * CustomerOrderDataService Object
	 * @var CustomerOrderDataService Object
	 */
	private $customerOrderDataService = null;
	
	/**
	 * CustomerOrderProductDataService Object
	 * @var CustomerOrderProductDataService Object
	 */
	private $customerOrderProductDataService = null;
	
	/**
	 * OrderStatusHistoryDataService Object
	 * @var OrderStatusHistoryDataService Object
	 */
	private $orderStatusHistoyDataService = null;
	
	/**
	 * Constructor of index
	 */
	public function __construct() {
		parent::__construct ();
		
		if ($this->authentication->getCurrentUserId () == null) {
			if ($this->ownerId != "") {
				$url = $this->getApplicationUrl () . "Login";
				CommonUtils::redirect ( $url );
				return - 1;
			} else {
				// Redirect to Page Not Found instead
				$url = Zend_Registry::get ( 'config' )->APPLICATION_URL . '/Browse/';
				CommonUtils::redirect ( $url );
				return - 1;
			}
		} else if ($this->authentication->getSession ()->userType != ROLE_MEMBER_USER && $this->ownerId != "" && $this->authentication->getSession ()->id != $this->ownerId) {
			// Logout this current user
			$url = $this->getApplicationUrl () . "MyAccount/logout";
			CommonUtils::redirect ( $url );
			return - 1;
		}
		
		// Init all Data Service
		$this->usersDataService = new UsersDataService ();
		$this->addressDataService = new AddressDataService ();
		$this->countryDataService = new CountryDataService ();
		$this->stateDataService = new StateDataService ();
		$this->customerOrderDataService = new CustomerOrderDataService ();
		$this->customerOrderProductDataService = new CustomerOrderProductDataService ();
		$this->orderStatusHistoyDataService = new OrderStatusHistoryDataService ();
		
		$this->setModuleName ( "MyAccount" );
		$this->smarty->assign ( "username", $this->authentication->getSession ()->firstName . " " . $this->authentication->getSession ()->lastName );
		
		$arrElement = array ();
		$countryList = $this->countryDataService->getItems ( $arrElement );
		$this->smarty->assign ( 'listCountry', $countryList );
	}
	
	/**
	 * Default Action of MyAccount Controller
	 */
	public function indexAction() {
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'MyAccount/my_account.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'MyAccount/m_my_account.tpl' );
		}
	}
	
	/**
	 *
	 * Logout Action
	 */
	public function logoutAction() {
		$usersDataService = new UsersDataService ();
		// Logout
		$usersDataService->logout ();
		
		//Unregister the CustomerSession Object
		if (isset ( $_SESSION [SESSION_CUSTOMER_ORDER] )) {
			// Unregister this session
			session_unregister ( SESSION_CUSTOMER_ORDER );
		}
		
		// Redirect to homepage
		//$url = Zend_Registry::get('config')->APPLICATION_URL . "/" . $this->ownerName . "/Login";
		$url = $this->getApplicationUrl () . "Login";
		CommonUtils::redirect ( $url );
	}
	
	/*
	 * Update user gereral information
	 */
	public function accountEditAction() {
		//Get Current User information
		$this->authentication = new Authentication ();
		$actionForm = $this->getPost ( 'actionForm', '' );
		
		// Only Normal User can update it
		if (! empty ( $actionForm ) && $actionForm == 'submit' && $this->isDemoMode == false) {
			$firstName = $this->getPost ( 'firstName', '' );
			$lastName = $this->getPost ( 'lastName', '' );
			$telephone = $this->getPost ( 'telephone', '' );
			$gender = $this->getPost ( 'gender', '' );
			$email = $this->getPost ( 'email', '' );
			$birthday = $this->getPost ( 'dob', '' );
			$usersEntity = $this->usersDataService->getById ( $this->authentication->getCurrentUserId () );
			$usersEntity->firstName = $firstName;
			$usersEntity->lastName = $lastName;
			$usersEntity->gender = $gender;
			$usersEntity->email = $email;
			$usersEntity->telephone = $telephone;
			$usersEntity->birthday = $birthday;
			$res = $this->usersDataService->update ( $usersEntity );
			$this->smarty->assign ( 'errorMessage', "Your Account information has been saved." );
		}
		$usersEntity = $this->usersDataService->getById ( $this->authentication->getCurrentUserId () );
		$this->smarty->assign ( 'usersEntity', $usersEntity );
		$sessionEntity = new SessionEntity ( $usersEntity );
		$this->authentication->saveSession ( $sessionEntity );
		
		if (isset ( $usersEntity )) {
			$firstName = $usersEntity->firstName;
			$lastName = $usersEntity->lastName;
			$telephone = $usersEntity->telephone;
			$birthday = $usersEntity->birthday;
			$gender = $usersEntity->gender;
			$email = $usersEntity->email;
			
			$this->smarty->assign ( 'firstName', $firstName );
			$this->smarty->assign ( 'lastName', $lastName );
			$this->smarty->assign ( 'telephone', $telephone );
			$this->smarty->assign ( 'gender', $gender );
			$this->smarty->assign ( 'email', $email );
			$this->smarty->assign ( 'birthday', $birthday );
		} else {
			// Go on to login page
			//$url = Zend_Registry::get('config')->APPLICATION_URL . "/" .$this->ownerName . '/MyAccount';
			$url = $this->getApplicationUrl () . 'MyAccount';
			CommonUtils::redirect ( $url );
			return - 1;
		}
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'MyAccount/account_edit.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'MyAccount/m_account_edit.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/MyAccount/account_edit.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 *
	 * Change Password Action
	 */
	public function changePasswordAction() {
		$isError = false;
		$error = "";
		$authenticate = new Authentication ();
		$usersEntity = $this->usersDataService->getById ( $authenticate->getCurrentUserId () );
		$this->smarty->assign ( 'usersEntity', $usersEntity );
		
		$actionForm = $this->getPost ( 'actionForm', '' );
		
		// Only Normal USer can edit password
		if (! empty ( $actionForm ) && $actionForm == 'submit' && $this->isDemoMode == false) {
			
			$oldPass = $this->getPost ( 'currentPassword', '' );
			$newPass = $this->getPost ( 'newPassword', '' );
			$oldPassEn = $authenticate->encryptPassword ( $oldPass );
			$newPassEn = $authenticate->encryptPassword ( $newPass );
			
			if ($oldPassEn == $usersEntity->password) {
				$usersEntity = $this->usersDataService->beforeUpdate ( $authenticate->getCurrentUserId () );
				$usersEntity->password = $newPassEn;
				$res = $this->usersDataService->update ( $usersEntity );
				
				$error = "Your password is changed succesfully!";
			} else {
				$isError = true;
				// Ignore to process this case. Only show a message
				$error = 'The password you type is not correct. Please try again!';
			}
		}
		
		$this->smarty->assign ( 'error', $error );
		$this->smarty->assign ( 'isError', $isError );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'MyAccount/change_password.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'MyAccount/m_change_password.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/MyAccount/change_password.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 *
	 * Address Book Action
	 */
	public function addressBookAction() {
		// Get Main Address Book
		$error = "";
		$mainAddressId = $this->authentication->getSession ()->mainAddressId;
		
		$mainAddress = $this->addressDataService->getById ( $mainAddressId );
		if (empty ( $mainAddress )) {
			$error = "Your address is empty. Please update it so that we can buy/sell products";
		}
		$limit = $this->getQuery ( 'limit', '' );
		if ($limit == "1") {
			$error = "Your maximum address is 5. Please delete or edit your old addresses";
		}
		
		$this->smarty->assign ( 'mainAddress', $mainAddress );
		$this->smarty->assign ( 'mainAddressId', $mainAddressId );
		
		//Get List of Address
		$arrElement = array ();
		$arrElement ["customerId"] = $this->authentication->getCurrentUserId ();
		$listAddress = $this->addressDataService->getItems ( $arrElement );
		$countAddress = $this->addressDataService->getTotals ( $arrElement );
		
		$this->smarty->assign ( 'listAddress', $listAddress );
		$this->smarty->assign ( 'errorMessage', ! empty ( $error ) ? $error : '' );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'MyAccount/address_book.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'MyAccount/m_address_book.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/MyAccount/address_book.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 *
	 * Order History Action
	 */
	public function orderHistoryAction() {
		//Get All Customer Order
		$arrElement = array ();
		$arrElement ['customers_id'] = $this->authentication->getCurrentUserId ();
		$arrElement [] = " orders_status > 0 ";
		$customerOrders = $this->customerOrderDataService->getItems ( $arrElement, " date_purchased DESC" );
		
		$this->smarty->assign ( 'listOrders', $customerOrders );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'MyAccount/order_history.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'MyAccount/m_order_history.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/MyAccount/order_history.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 *
	 * Add Address Action
	 */
	public function addAddressAction() {
		
		// Get action method and check it
		$actionForm = $this->getPost ( 'actionForm', '' );
		
		$type = $this->getQuery ( 'type', '' );
		if ($type == "") {
			$type = $this->getPost ( 'type', '' );
		}
		if ($type == ADDRESS_SHIPPING) {
			$this->smarty->assign ( 'title', "Change Shipping Address" );
		} else if ($type == ADDRESS_BILLING) {
			$this->smarty->assign ( 'title', "Change Billing Address" );
		} else {
			$this->smarty->assign ( 'title', "New Address Book Entry" );
		}
		$this->smarty->assign ( 'type', $type );
		
		$confirm = $this->getQuery ( 'confirm', '' );
		$this->smarty->assign ( 'confirm', $confirm );
		
		//Check if totals address is > 5
		$arrElement = array ();
		$arrElement ['customerId'] = $this->authentication->getCurrentUserId ();
		$totalAddress = $this->addressDataService->getTotals ( $arrElement );
		
		if ($totalAddress >= 5) {
			//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/MyAccount/addressBook/limit/1";
			$url = $this->getApplicationUrl () . "MyAccount/addressBook/limit/1";
			CommonUtils::redirect ( $url );
		}
		
		if (! empty ( $actionForm ) && $actionForm == 'submit' && $this->isDemoMode == false) {
			
			$firstName = $this->getPost ( 'firstName', '' );
			$lastName = $this->getPost ( 'lastName', '' );
			$birthday = $this->getPost ( 'dob', '' );
			$country = $this->getPost ( 'country', '' );
			$gender = $this->getPost ( 'gender', '' );
			$city = $this->getPost ( 'city', '' );
			$street = $this->getPost ( 'street', '' );
			$company = $this->getPost ( 'company', '' );
			$zipCode = $this->getPost ( 'zipCode', '' );
			$email = $this->getPost ( 'email', '' );
			$telephone = $this->getPost ( 'telephone', '' );
			$state = $this->getPost ( 'state', '' );
			$primary = $this->getPost ( 'primary', '' );
			
			// check
			if (! empty ( $street )) {
				$authentication = new Authentication ();
				try {
					// Save data into database
					$addressEntity = $this->addressDataService->beforeCreate ();
					$addressEntity->gender = $gender;
					$addressEntity->company = $company;
					$addressEntity->firstName = $firstName;
					$addressEntity->lastName = $lastName;
					$addressEntity->street = $street;
					$addressEntity->gender = $gender;
					$addressEntity->postcode = $zipCode;
					$addressEntity->city = $city;
					$addressEntity->stateId = $state;
					$addressEntity->countryId = $country;
					$addressEntity->customerId = $this->authentication->getCurrentUserId ();
					$addressId = $this->addressDataService->create ( $addressEntity );
					
					if ($primary == "on") {
						$currentUser = $this->usersDataService->getById ( $this->authentication->getCurrentUserId () );
						$currentUser->mainAddressId = $addressId;
						$this->usersDataService->update ( $currentUser );
						
						// Save to SESSION
						$sessionEntity = new SessionEntity ( $currentUser );
						$this->authentication->saveSession ( $sessionEntity );
					}
					
					// Redirect to edit page
					//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/MyAccount/addressBook";
					$url = $this->getApplicationUrl () . "MyAccount/addressBook";
					CommonUtils::redirect ( $url );
					exit ();
				} catch ( Exception $ex ) {
					$isError = true;
					$error = 'The address cannot create successfully. Error Code = ' . $ex->getCode ();
				}
			} else {
				$isError = true;
				$error = 'Please fill in all required fields';
			}
		}
		
		if (! empty ( $actionForm ) && $actionForm == 'change' && $type != "" && $this->isDemoMode == false) {
			
			$address = $this->getPost ( 'address', '' );
			$confirm = $this->getPost ( 'confirm', '' );
			
			$customerSession = $this->authentication->getCustomerOrderSession ();
			if ($type == ADDRESS_BILLING) {
				$customerSession->billingAddressId = $address;
				$this->authentication->saveCustomerOrderSession ( $customerSession );
				
				if (intval ( $confirm ) == 1) {
					//Redirect to Shipping information
					//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product/confirmOrder";
					$url = $this->getApplicationUrl () . "Product/confirmOrder";
					CommonUtils::redirect ( $url );
				} else {
					//Redirect to Shipping information
					//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product/checkoutPayment";
					$url = $this->getApplicationUrl () . "Product/checkoutPayment";
					CommonUtils::redirect ( $url );
				}
				return - 1;
			} else if ($type == ADDRESS_SHIPPING) {
				$customerSession->shippingAddressId = $address;
				$this->authentication->saveCustomerOrderSession ( $customerSession );
				
				if (intval ( $confirm ) == 1) {
					//Redirect to Shipping information
					//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product/confirmOrder";
					$url = $this->getApplicationUrl () . "Product/confirmOrder";
					CommonUtils::redirect ( $url );
				} else {
					//Redirect to Billing information
					//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/Product/checkoutShipping";
					$url = $this->getApplicationUrl () . "Product/checkoutShipping";
					CommonUtils::redirect ( $url );
				}
				return - 1;
			}
			$customerSession = $this->authentication->getCustomerOrderSession ();
		}
		
		unset ( $arrElement );
		$arrElement = array ();
		$countryId = $this->getQuery ( 'countryId', '' );
		
		$stateList = array ();
		if (! empty ( $countryId )) {
			$arrElement ['countryId'] = $countryId;
			$stateList = $this->stateDataService->getItems ( $arrElement );
			$this->smarty->assign ( 'listState', $stateList );
			$this->smarty->assign ( 'countryId', $countryId );
		}
		
		$arrElement = array ();
		$arrElement ["customerId"] = $this->authentication->getCurrentUserId ();
		$listAddress = $this->addressDataService->getItems ( $arrElement );
		$countAddress = $this->addressDataService->getTotals ( $arrElement );
		
		$this->smarty->assign ( 'listAddress', $listAddress );
		
		$this->smarty->assign ( 'listState', $stateList );
		$this->smarty->assign ( 'type', $type );
		$this->smarty->assign ( 'errorMessage', isset ( $error ) ? $error : '' );
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'MyAccount/add_address.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'MyAccount/m_add_address.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/MyAccount/add_address.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 *
	 * Edit Address Action
	 */
	public function editAddressAction() {
		// Error flag
		$isError = false;
		$error = "";
		
		// Get id of page
		$id = $this->getPost ( 'id' );
		if (empty ( $id )) {
			$id = $this->getQuery ( 'id' );
		}
		// If the id of page does not exist, go on to view list page
		if (empty ( $id ) || ! is_numeric ( $id )) {
			$this->indexAction ();
			return false;
		}
		
		$id = intval ( $id );
		
		// Get data
		$addressEntity = $this->addressDataService->getById ( $id );
		
		// check data
		if (empty ( $addressEntity )) {
			$this->indexAction ();
			return false;
		}
		
		// Get action method and check it
		$actionForm = $this->getPost ( 'actionForm', '' );
		
		// submit
		if (! empty ( $actionForm ) && $actionForm == 'submit' && $this->isDemoMode == false) {
			$firstName = $this->getPost ( 'firstName', '' );
			$lastName = $this->getPost ( 'lastName', '' );
			$birthday = $this->getPost ( 'dob', '' );
			$country = $this->getPost ( 'country', '' );
			$gender = $this->getPost ( 'gender', '' );
			$city = $this->getPost ( 'city', '' );
			$street = $this->getPost ( 'street', '' );
			$company = $this->getPost ( 'company', '' );
			$zipCode = $this->getPost ( 'zipCode', '' );
			$email = $this->getPost ( 'email', '' );
			$telephone = $this->getPost ( 'telephone', '' );
			$state = $this->getPost ( 'state', '' );
			$primary = $this->getPost ( 'primary', '' );
			
			$addressEntity->gender = $gender;
			$addressEntity->company = $company;
			$addressEntity->firstName = $firstName;
			$addressEntity->lastName = $lastName;
			$addressEntity->street = $street;
			$addressEntity->gender = $gender;
			$addressEntity->postcode = $zipCode;
			$addressEntity->city = $city;
			$addressEntity->stateId = $state;
			$addressEntity->countryId = $country;
			
			// check
			if (! empty ( $street )) {
				try {
					$res = $this->addressDataService->update ( $addressEntity );
					
					if ($primary == "on") {
						$currentUser = $this->usersDataService->getById ( $this->authentication->getCurrentUserId () );
						$currentUser->mainAddressId = $addressEntity->id;
						$this->usersDataService->update ( $currentUser );
						
						// Save to SESSION
						$sessionEntity = new SessionEntity ( $currentUser );
						$this->authentication->saveSession ( $sessionEntity );
					
					}
					
					$isError = false;
					
					// Show a message
					$error = 'The address has been updated successfully';
				} catch ( Exception $ex ) {
					
					// Ignore to process this case. Only show a message
					$error = 'The item cannot create successfully. Error Code = ' . $ex->getCode ();
					$isError = true;
				}
			} else {
				$isError = true;
				
				$error = 'Please fill in all required fields';
			}
		}
		$countryId = $this->getQuery ( 'countryId', '' );
		if (empty ( $countryId )) {
			$countryId = $addressEntity->countryId;
		}
		$stateList = array ();
		if (! empty ( $countryId )) {
			$arrElement ['countryId'] = $countryId;
			$stateList = $this->stateDataService->getItems ( $arrElement );
			$this->smarty->assign ( 'listState', $stateList );
			$this->smarty->assign ( 'countryId', $countryId );
		}
		
		$this->smarty->assign ( 'listState', $stateList );
		
		$this->smarty->assign ( 'errorMessage', isset ( $error ) ? $error : '' );
		
		$this->smarty->assign ( 'id', $addressEntity->id );
		$this->smarty->assign ( 'firstName', $addressEntity->firstName );
		$this->smarty->assign ( 'lastName', $addressEntity->lastName );
		$this->smarty->assign ( 'company', $addressEntity->company );
		$this->smarty->assign ( 'gender', $addressEntity->gender );
		$this->smarty->assign ( 'street', $addressEntity->street );
		$this->smarty->assign ( 'zipCode', $addressEntity->postcode );
		$this->smarty->assign ( 'stateId', $addressEntity->stateId );
		$this->smarty->assign ( 'city', $addressEntity->city );
		$this->smarty->assign ( 'countryId', $addressEntity->countryId );
		
		if ($this->isMobileMode == false) {
			// Assign Smarty Content
			$this->assignSmartyContent ( 'MyAccount/edit_address.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'MyAccount/m_edit_address.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/MyAccount/edit_address.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}
	
	/**
	 *
	 * Delete Address Action
	 */
	public function deleteAddressAction() {
		// Get Id of page
		$id = $this->getQuery ( 'id', 0 );
		
		if (! empty ( $id ) && is_numeric ( $id ) && $this->isDemoMode == false) {
			
			$id = intval ( $id );
			
			//$currentUser = $this->authentication->getSession();
			$currentUser = $this->usersDataService->getById ( $this->authentication->getCurrentUserId () );
			$mainAddressId = $currentUser->mainAddressId;
			//Update mainAddressId
			if ($id == $mainAddressId) //Main Address is deleted
{
				$arrElement = array ();
				$arrElement ['customerId'] = $this->authentication->getCurrentUserId ();
				$arrElement [] = " id != {$id}";
				$addressList = $this->addressDataService->getItems ( $arrElement );
				if (count ( $addressList ) > 0) {
					$currentUser->mainAddressId = $addressList [0]->id;
					$sessionEntity = new SessionEntity ( $currentUser );
					$this->authentication->saveSession ( $sessionEntity );
					// Delete Address
					$res = $this->addressDataService->del ( $id );
				
				} else {
					//Do not allow to delete this address as this is the only one address
					$error = "This main address cannot be deleted.";
					$this->smarty->assign ( 'errorMessage', empty ( $error ) ? $error : '' );
					$this->addressBookAction ();
					return;
				}
			
			} else {
				// Delete Address
				$res = $this->addressDataService->del ( $id );
			
			}
		}
		// Redirect to edit page
		//$url = Zend_Registry::get('config')->APPLICATION_URL .'/'.$this->ownerName .'/MyAccount/addressBook';
		$url = $this->getApplicationUrl () . 'MyAccount/addressBook';
		CommonUtils::redirect ( $url );
	}
	
	/**
	 * Change Customer Address Action
	 */
	public function changeAddressAction() {
		
		// Get action method and check it
		$actionForm = $this->getPost ( 'actionForm', '' );
		
		//Check if totals address is > 5
		$arrElement = array ();
		$arrElement ['customerId'] = $this->authentication->getCurrentUserId ();
		$totalAddress = $this->addressDataService->getTotals ( $arrElement );
		
		if ($totalAddress >= 5) {
			//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/MyAccount/addressBook/limit/1";
			$url = $this->getApplicationUrl () . "MyAccount/addressBook/limit/1";
			CommonUtils::redirect ( $url );
		}
		
		if (! empty ( $actionForm ) && $actionForm == 'submit' && $this->isDemoMode == false) {
			
			$firstName = $this->getPost ( 'firstName', '' );
			$lastName = $this->getPost ( 'lastName', '' );
			$birthday = $this->getPost ( 'dob', '' );
			$country = $this->getPost ( 'country', '' );
			$gender = $this->getPost ( 'gender', '' );
			$city = $this->getPost ( 'city', '' );
			$street = $this->getPost ( 'street', '' );
			$company = $this->getPost ( 'company', '' );
			$zipCode = $this->getPost ( 'zipCode', '' );
			$email = $this->getPost ( 'email', '' );
			$telephone = $this->getPost ( 'telephone', '' );
			$state = $this->getPost ( 'state', '' );
			$primary = $this->getPost ( 'primary', '' );
			
			// check
			if (! empty ( $street )) {
				$authentication = new Authentication ();
				try {
					// Save data into database
					$addressEntity = $this->addressDataService->beforeCreate ();
					$addressEntity->gender = $gender;
					$addressEntity->company = $company;
					$addressEntity->firstName = $firstName;
					$addressEntity->lastName = $lastName;
					$addressEntity->street = $street;
					$addressEntity->gender = $gender;
					$addressEntity->postcode = $zipCode;
					$addressEntity->city = $city;
					$addressEntity->stateId = $state;
					$addressEntity->countryId = $country;
					$addressEntity->customerId = $this->authentication->getCurrentUserId ();
					$addressId = $this->addressDataService->create ( $addressEntity );
					
					if ($primary == "on") {
						$currentUser = $this->usersDataService->getById ( $this->authentication->getCurrentUserId () );
						$currentUser->mainAddressId = $addressId;
						$this->usersDataService->update ( $currentUser );
						
						// Save to SESSION
						$sessionEntity = new SessionEntity ( $currentUser );
						$this->authentication->saveSession ( $sessionEntity );
					}
					
					// Redirect to edit page
					//$url = Zend_Registry::get('config')->APPLICATION_URL . '/' . $this->ownerName . "/MyAccount/addressBook";
					$url = $this->getApplicationUrl () . "MyAccount/addressBook";
					CommonUtils::redirect ( $url );
					exit ();
				} catch ( Exception $ex ) {
					$isError = true;
					$error = 'The address cannot create successfully. Error Code = ' . $ex->getCode ();
				}
			} else {
				$isError = true;
				$error = 'Please fill in all required fields';
			}
		}
		unset ( $arrElement );
		$arrElement = array ();
		$countryId = $this->getQuery ( 'countryId', '' );
		
		$stateList = array ();
		if (! empty ( $countryId )) {
			$arrElement ['countryId'] = $countryId;
			$stateList = $this->stateDataService->getItems ( $arrElement );
			$this->smarty->assign ( 'listState', $stateList );
			$this->smarty->assign ( 'countryId', $countryId );
		}
		
		$this->smarty->assign ( 'listState', $stateList );
		$this->smarty->assign ( 'errorMessage', isset ( $error ) ? $error : '' );
		
		// Assign Smarty Content
		if ($this->isMobileMode == false) {
			$this->assignSmartyContent ( 'MyAccount/change_address.tpl' );
		} else {
			$this->assignSmartyMobileContent ( 'MyAccount/m_change_address.tpl' );
		}
	
		//$this->smarty->assign('SMARTY_CONTENT_PATH', 'template1/MyAccount/change_address.tpl');
	//$this->smarty->display(APPLICATION_PATH . '/Layouts/template1/MainLayout.tpl');
	}

}
